--
-- Author: gnar
-- Date: 2015-12-30 16:26:43
--
local ChatLayerCCB = {}  --自己用的数据（owner不会用到） 存在这个里面
ccb.ChatLayerCCB = ChatLayerCCB
local owner = {}  --owner中会用到的数据 都存在这个里面
local eventDispatcher = cc.Director:getInstance():getEventDispatcher()

function ChatLayerCCB.initWithTarget(target)
	owner = target
	_initSmallWin()
	_initMainWin()

end

function ChatLayerCCB.showChatCall(sender,controlEvent,self)
 	owner.isChatShow = true
end

function ChatLayerCCB.hideChatCall(sender,controlEvent,self)
 	owner.isChatShow = false
end

function ChatLayerCCB.sendCall(sender,controlEvent,self)

    local chatItem = {}
    chatItem.channelIdx = ManagerChatData.currentOpenedChannel
    
    local sname = ManagerUserData:getActivityCharacterForChoose().name
    local defaultNames = {Word(1).ChatLayerCCB_02, sname}
    chatItem.senderName = defaultNames[ManagerUserData.loginMode]

    chatItem.msg = TextPaser.inputText2EncodeMsg(ChatLayerCCB.inputText, {})

    ManagerChatData:sendChat(chatItem) 
end

function ChatLayerCCB.onNewChat(chatItem)

    print("test 1221122",chatItem.senderName,chatItem.channelIdx,chatItem.msg)
    _updateTextWin()

end

function ChatLayerCCB.systemCall(sender,controlEvent,self)
    ManagerChatData.currentOpenedChannel = ManagerChatData.channels.system
    _updateTextWin()
end

function ChatLayerCCB.currentCall(sender,controlEvent,self)
    ManagerChatData.currentOpenedChannel = ManagerChatData.channels.current
    _updateTextWin()
end

function ChatLayerCCB.worldCall(sender,controlEvent,self)
    ManagerChatData.currentOpenedChannel = ManagerChatData.channels.world
    _updateTextWin()
end

function ChatLayerCCB.teamCall(sender,controlEvent,self)
    ManagerChatData.currentOpenedChannel = ManagerChatData.channels.team
    _updateTextWin()
end

function ChatLayerCCB.menpaiCall(sender,controlEvent,self)
    ManagerChatData.currentOpenedChannel = ManagerChatData.channels.menpai
    _updateTextWin()
end

function ChatLayerCCB.unionCall(sender,controlEvent,self)
    ManagerChatData.currentOpenedChannel = ManagerChatData.channels.union
    _updateTextWin()
end

_initSmallWin = function()
	
	if not ChatLayerCCB.smallWinListener then
		local function onTouchBegan(touch, event)
	    	return touchBegan(touch, event)  
		end
		local function onTouchEnded(touch, event)
			if not owner.isChatShow then
			 	ChatLayerCCB["mAnimationManager"]:runAnimationsForSequenceNamedTweenDuration("showChat", 0)
			end
		end
		ChatLayerCCB.smallWinListener = cc.EventListenerTouchOneByOne:create()
		ChatLayerCCB.smallWinListener:setSwallowTouches(true)
		ChatLayerCCB.smallWinListener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN )
		ChatLayerCCB.smallWinListener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED )
	end
	
	eventDispatcher:addEventListenerWithSceneGraphPriority(ChatLayerCCB.smallWinListener, ChatLayerCCB.smallWin)

end

_initMainWin = function()
    local listener = cc.EventListenerTouchOneByOne:create()
    listener:registerScriptHandler(function(touch, event)return touchBegan(touch, event) end, cc.Handler.EVENT_TOUCH_BEGAN)
    listener:setSwallowTouches(true)
	--eventDispatcher:addEventListenerWithFixedPriority(listener,Constants.chatNodeLisPriority)
    eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ChatLayerCCB.mainWin)

    _initEditBox()
	_initTextWin()
end

_initEditBox = function()

    --editbox
    local editBoxSize = cc.size(ChatLayerCCB.inputBox:getContentSize().width-30, 40)
    local editBox  = cc.EditBox:create(editBoxSize, cc.Scale9Sprite:create())
    
    editBox:setPosition(15, ChatLayerCCB.inputBox:getContentSize().height / 2)
    editBox:setFontSize(30)
    editBox:setPlaceHolder(Word(1).ChatLayerCCB_01)
    editBox:setMaxLength(40)
    editBox:setAnchorPoint(cc.p(0, 0.5))
    editBox:setFontColor(Constants.color2 )
    editBox:setPlaceholderFontColor(Constants.color2 )
    editBox:setPlaceholderFontSize(30)
    editBox:setReturnType(cc.KEYBOARD_RETURNTYPE_DONE)
    editBox:setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE)

    editBox:addTo(ChatLayerCCB.inputBox)

    --Handler
    local editBoxTextEventHandle = function(strEventName,pSender)
        local edit = pSender
        local strFmt 
        if strEventName == "began" then
        elseif strEventName == "ended" then
        elseif strEventName == "return" then
        elseif strEventName == "changed" then
            strFmt = string.format("editBox %p TextChanged, text: %s ", edit, edit:getText())
           	ChatLayerCCB.inputText = edit:getText()
            print(strFmt)
        end
    end

    editBox:registerScriptEditBoxHandler(editBoxTextEventHandle)

end


--------------------------textwin tableview----------------------------------------------
  
_isTableViewTouchEnable = function()
    
    local listNum = #ManagerChatData:getChatListByType(ManagerChatData.currentOpenedChannel) 
    if listNum > 0 then
        local t = ChatLayerCCB.tableView
        local cellAtIndex0 = t:cellAtIndex(0)
        local _ , cell0Height = _cellSizeForTable(t, 0)
        local cellAtIndex0IsNotTop = cellAtIndex0 and cellAtIndex0:getPositionY() + cell0Height < t:getViewSize().height 
        return  not cellAtIndex0IsNotTop 
    end

    return false
end

_initTextWin = function()
	
	local tableView = cc.TableView:create(cc.size(0,0))
    tableView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
    tableView:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN)
    tableView:setViewSize(cc.size(ChatLayerCCB.textWin:getContentSize().width - 20, ChatLayerCCB.textWin:getContentSize().height - 30))
    tableView:setPosition(cc.p(10,15))

    tableView:setDelegate()
    ChatLayerCCB.textWin:addChild(tableView)

    --registerScriptHandler functions must be before the reloadData funtion
    tableView:registerScriptHandler(_numberOfCellsInTableView,cc.NUMBER_OF_CELLS_IN_TABLEVIEW)  --Cell的行数
    tableView:registerScriptHandler(_scrollViewDidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL)--滚动时的事件
    tableView:registerScriptHandler(_scrollViewDidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM)
    tableView:registerScriptHandler(_tableCellTouched,cc.TABLECELL_TOUCHED) --触碰到Cell的事件
    tableView:registerScriptHandler(_cellSizeForTable,cc.TABLECELL_SIZE_FOR_INDEX) --Cell的尺寸
    tableView:registerScriptHandler(_tableCellAtIndex,cc.TABLECELL_SIZE_AT_INDEX) --Cell的内容

    ChatLayerCCB.tableView = tableView
    ChatLayerCCB.tableView:reloadData()
    ChatLayerCCB.tableView:setTouchEnabled(_isTableViewTouchEnable())

end

_numberOfCellsInTableView = function()
    
    local currentOpenedChannelList = ManagerChatData:getChatListByType(ManagerChatData.currentOpenedChannel)  
    return #currentOpenedChannelList

end

_scrollViewDidScroll = function(view)

end

_scrollViewDidZoom = function(view)

end

_tableCellTouched = function(table,cell)

end

_cellSizeForTable = function(table, idx)
    
    local idx  = idx + 1 
    local currentOpenedChannelList = ManagerChatData:getChatListByType(ManagerChatData.currentOpenedChannel)  
    local chatItem =  currentOpenedChannelList[idx]
    return ChatLayerCCB.textWin:getContentSize().width,chatItem.height
end

_tableCellAtIndex = function(t, idx)
    
    local idx  = idx + 1 
    local cell = t:dequeueCell()   --得到Cell 

    local currentOpenedChannelList = ManagerChatData:getChatListByType(ManagerChatData.currentOpenedChannel)  

    local chatItem =  currentOpenedChannelList[idx]
    --chatItem.idx =  idx
    local item = nil
    if nil == cell then  
        cell = cc.TableViewCell:new()
        local width = ChatLayerCCB.textWin:getContentSize().width - 40
        local encodeMsg = TextPaser.attachSrcForMsg(chatItem.msg, chatItem.channelIdx, chatItem.senderName)
        item  = TextPaser.encodeMsg2RichText(encodeMsg, width)
        item:align(cc.p(0,0), 20, chatItem.height)
        cell:addChild(item,10,100010)
    else
        item = cell:getChildByTag(100010)
        item:removeFromParent()
        local width = ChatLayerCCB.textWin:getContentSize().width - 40
        local encodeMsg = TextPaser.attachSrcForMsg(chatItem.msg, chatItem.channelIdx, chatItem.senderName)
        item  = TextPaser.encodeMsg2RichText(encodeMsg, width)
        item:align(cc.p(0,0), 20, chatItem.height)
        cell:addChild(item,10,100010)
    end

    return cell
end

_updateTextWin = function(scrollOffsetY)
  
    _refreshTable(scrollOffsetY)

end

_refreshTable = function(scrollOffsetY)

    ChatLayerCCB.tableView:reloadData()  
    ChatLayerCCB.tableView:setTouchEnabled(_isTableViewTouchEnable())

    local tScrollOffsetY = scrollOffsetY or 0  
    
    ChatLayerCCB.tableView:setContentOffset(cc.p(0, tScrollOffsetY),false)  
    
end
----------------------------------------------------
return ChatLayerCCB